package com.tebiecloud.ali.server.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.ObjectMetadata;
import com.tebiecloud.ali.client.constants.AliConstants;
import com.tebiecloud.ali.server.properties.AliYunOSSProperties;
import com.tebiecloud.ali.server.service.AliOssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;

/**
 * oss服务接口
 * @Author: tebie
 * @Date: 2019-09-24 09:49
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class AliOssServiceImpl implements AliOssService {

    @Autowired
    private AliYunOSSProperties aliYunOSSProperties;

    @Override
    public String upload(String ossKey, InputStream inputStream) {
        OSSClient ossClient = null;
        try {
            DefaultCredentialProvider DefaultCredentialProvider = new DefaultCredentialProvider(aliYunOSSProperties.getAccessKeyId(), aliYunOSSProperties.getAccessKeySecret());
            ossClient = new OSSClient(AliConstants.ALI_ENDPOINT, DefaultCredentialProvider, null);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            ossClient.putObject(aliYunOSSProperties.getBucketName(), ossKey, inputStream);
        }catch (OSSException oe) {
            log.error("xiaoc>> ali oss 图片上传失败，code: {}, request ID: {}, host ID: {}, message", oe.getErrorCode(), oe.getRequestId(), oe.getHostId(), oe.getErrorMessage());
            oe.printStackTrace();
            throw new RuntimeException("图片上传失败");
        } catch (ClientException ce) {
            log.error("xiaoc>> ali oss 图片上传失败，message", ce.getMessage());
            throw new RuntimeException("图片上传失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        String data = aliYunOSSProperties.getDomain() + "/" + ossKey;
		return data;
    }

}
